package com.klm.easymq.listener;

import com.klm.easymq.core.MonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 消费者生命周期监听器
 * 自动记录消费者的启动、停止、错误等事件
 */
@Slf4j
@Component
public class ConsumerLifecycleListener implements ApplicationListener<ContextRefreshedEvent> {
    
    @Autowired
    private MonitorService monitorService;
    
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private String applicationId;
    private String hostAddress;
    
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            // 获取应用信息
            applicationId = event.getApplicationContext().getApplicationName();
            if (applicationId == null || applicationId.isEmpty()) {
                applicationId = "unknown-application";
            }
            
            hostAddress = InetAddress.getLocalHost().getHostAddress();
            
            // 记录应用启动事件
            String details = String.format("Application started on %s at %s", 
                    hostAddress, LocalDateTime.now().format(formatter));
            
            monitorService.recordConsumerLifecycle(
                applicationId, 
                "application", 
                "application", 
                "START", 
                details
            );
            
            log.info("Recorded application start event: applicationId={}, hostAddress={}", 
                    applicationId, hostAddress);
            
        } catch (Exception e) {
            log.error("Failed to record application start event", e);
        }
    }
    
    /**
     * 记录消费者启动事件
     */
    public void recordConsumerStart(String consumerId, String group, String topic) {
        try {
            String details = String.format("Consumer started on %s at %s", 
                    hostAddress, LocalDateTime.now().format(formatter));
            
            monitorService.recordConsumerLifecycle(consumerId, group, topic, "START", details);
            
            log.info("Recorded consumer start event: consumerId={}, group={}, topic={}", 
                    consumerId, group, topic);
            
        } catch (Exception e) {
            log.error("Failed to record consumer start event: consumerId={}", consumerId, e);
        }
    }
    
    /**
     * 记录消费者停止事件
     */
    public void recordConsumerStop(String consumerId, String group, String topic) {
        try {
            String details = String.format("Consumer stopped on %s at %s", 
                    hostAddress, LocalDateTime.now().format(formatter));
            
            monitorService.recordConsumerLifecycle(consumerId, group, topic, "STOP", details);
            
            log.info("Recorded consumer stop event: consumerId={}, group={}, topic={}", 
                    consumerId, group, topic);
            
        } catch (Exception e) {
            log.error("Failed to record consumer stop event: consumerId={}", consumerId, e);
        }
    }
    
    /**
     * 记录消费者错误事件
     */
    public void recordConsumerError(String consumerId, String group, String topic, String errorMsg) {
        try {
            String details = String.format("Consumer error on %s at %s: %s", 
                    hostAddress, LocalDateTime.now().format(formatter), errorMsg);
            
            monitorService.recordConsumerLifecycle(consumerId, group, topic, "ERROR", details);
            
            log.warn("Recorded consumer error event: consumerId={}, group={}, topic={}, error={}", 
                    consumerId, group, topic, errorMsg);
            
        } catch (Exception e) {
            log.error("Failed to record consumer error event: consumerId={}", consumerId, e);
        }
    }
    
    /**
     * 记录消费者重连事件
     */
    public void recordConsumerReconnect(String consumerId, String group, String topic) {
        try {
            String details = String.format("Consumer reconnected on %s at %s", 
                    hostAddress, LocalDateTime.now().format(formatter));
            
            monitorService.recordConsumerLifecycle(consumerId, group, topic, "RECONNECT", details);
            
            log.info("Recorded consumer reconnect event: consumerId={}, group={}, topic={}", 
                    consumerId, group, topic);
            
        } catch (Exception e) {
            log.error("Failed to record consumer reconnect event: consumerId={}", consumerId, e);
        }
    }
    
    /**
     * 记录连接状态变化
     */
    public void recordConnectionStatus(String adapterType, String status, String errorMsg) {
        try {
            monitorService.recordConnectionStatus(adapterType, status, errorMsg);
            
            log.info("Recorded connection status: adapterType={}, status={}", adapterType, status);
            
        } catch (Exception e) {
            log.error("Failed to record connection status: adapterType={}, status={}", adapterType, status, e);
        }
    }
    
    /**
     * 应用停止时记录事件
     */
    @PreDestroy
    public void onApplicationStop() {
        try {
            String details = String.format("Application stopped on %s at %s", 
                    hostAddress, LocalDateTime.now().format(formatter));
            
            monitorService.recordConsumerLifecycle(
                applicationId, 
                "application", 
                "application", 
                "STOP", 
                details
            );
            
            log.info("Recorded application stop event: applicationId={}, hostAddress={}", 
                    applicationId, hostAddress);
            
        } catch (Exception e) {
            log.error("Failed to record application stop event", e);
        }
    }
} 